<script setup lang="ts">
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  MinusOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";
import { h, onMounted, ref, watch } from "vue";
import { template } from "/@/api/Carbon module/Carbon account/ESG/template";
// 左侧树数据
const treeData: any = ref([]);

// 右侧树数据
const rightTreeData = ref([
  {
    title: "前言",
    key: "0",
    children: [
      {
        title: "1.1、公司简介",
        key: "1",
        type: "介绍企业的使命、愿景和核心价值观",
        children: [],
      },
      {
        title: "1.2、报告概述",
        key: "2",
        type: "概述报告的目的、范围和编制方法",
        children: [],
      },
    ],
  },
  {
    title: "环境（Environmental）",
    key: "3",
    children: [
      {
        title: "2.1、碳排放管理",
        key: "3-1",
        children: [],
        type: "详细说明企业在减少碳足迹方面的措施和成就",
      },
      {
        title: "2.2、能源使用",
        key: "3-2",
        children: [],
        type: "介绍公司在提高能源效率和使用可再生能源方面的努力",
      },
      {
        title: "2.3、资源管理",
        key: "3-3",
        children: [],
        type: "包括水资源管理、废弃物处理和材料使用等方面的策略和成果",
      },
    ],
  },
  {
    title: "社会（Social）",
    key: "4",
    children: [
      {
        title: "3.1、员工福利",
        key: "4-1",
        children: [],
        type: "涵盖员工培训、职业发展、健康与安全等方面的政策和实践",
      },
      {
        title: "3.2、社区参与",
        key: "4-2",
        children: [],
        type: "描述企业在支持社区发展、教育和公益项目方面的贡献",
      },
      {
        title: "3.3、客户责任",
        key: "4-3",
        children: [],
        type: "包括数据隐私保护、客户服务和产品责任等内容",
      },
    ],
  },
  {
    title: "治理（Governance）",
    key: "5",
    children: [
      {
        title: "4.1、公司治理结构",
        key: "5-1",
        children: [],
        type: "介绍董事会组成、独立性和治理政策",
      },
      {
        title: "4.2、商业道德",
        key: "5-2",
        children: [],
        type: "详细说明反腐败措施、合规管理和道德规范",
      },
      {
        title: "4.3、股东权益",
        key: "5-3",
        children: [],
        type: "描述企业如何保护和沟通股东权益",
      },
    ],
  },
  {
    title: "可持续发展目标",
    key: "6",
    children: [
      {
        title: "5.1、长期目标",
        key: "6-1",
        children: [],
        type: "企业在环境、社会和治理方面的长期目标和愿景",
      },
      {
        title: "5.2、进展报告",
        key: "6-2",
        children: [],
        type: "展示企业在实现这些目标方面的进展和未来计划",
      },
    ],
  },
  {
    title: "附录",
    key: "7",
    children: [
      { title: "6.1、数据披露", key: "7-1", children: [], type: "详细的ESG数据和指标" },
      {
        title: "6.2、报告方法",
        key: "7-2",
        children: [],
        type: "说明报告编制的方法和标准",
      },
      {
        title: "6.3、利益相关方参与",
        key: "7-3",
        children: [],
        type: "描述利益相关方的参与和反馈机制",
      },
    ],
  },
]);

const title = ref(""); // 右侧标题区域显示的名称
const expandedKeys = ref<string[]>(["0-0", "0-0-0"]);
const checkedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]); // 选中的节点
const selectedNodeKey = ref<string | null>(null); // 当前选中的节点key
const inputValue = ref(""); // 用于存储输入框的值
const showModal = ref(false); // 控制模态框的显示
const isChildNode = ref(false); // 控制添加节点类型（是否为下级节点）
const findTypeByKey = (key: string): string | undefined => {
  const node = findNodePosition(key, rightTreeData.value);
  return node?.parent?.children[node.index]?.type;
};
const value = ref("");
watch(expandedKeys, () => {
  console.log("expandedKeys", expandedKeys);
});

watch(checkedKeys, () => {
  console.log("checkedKeys", checkedKeys);
});

watch(selectedKeys, (newKeys) => {
  if (newKeys.length > 0) {
    const key = newKeys[0];
    selectedNodeKey.value = key;
    // 只在右侧树节点选择时不更新标题
  } else {
    selectedNodeKey.value = null;
  }
});

let clickTimer = null;
const doubleClickThreshold = 300; // 300ms
function transformData(data: any) {
  return data.map((node: any) => ({
    title: node.templateName,
    key: node.templateId.toString(),
    children: node.children ? transformData(node.children) : null, // 递归处理多层 children
  }));
}
async function queryData() {
  try {
    let queryResult = await template.query();
    treeData.value = transformData(queryResult.data);
  } catch (error) {
    console.log(error);
  }
}
const handleClick = (event, node) => {
  if (clickTimer) {
    clearTimeout(clickTimer);
    clickTimer = null;
    handleDoubleClick(node);
  } else {
    clickTimer = setTimeout(() => {
      clickTimer = null;
    }, doubleClickThreshold);
  }
};

const handleDoubleClick = (node) => {
  const { key } = node;
  selectedKeys.value = [key];
  title.value = node.dataRef.title;
};

// 查找节点在树中的位置
const findNodePosition = (
  key: string,
  nodes: any[]
): { parent: any; index: number } | null => {
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.key === key) {
      return { parent: null, index: i };
    }
    if (node.children) {
      const result = findNodePosition(key, node.children);
      if (result) {
        return { parent: node, index: result.index };
      }
    }
  }
  return null;
};

// 打开模态框
const openModal = (isChild: boolean) => {
  inputValue.value = ""; // 清空输入框
  isChildNode.value = isChild;
  showModal.value = true;
};

// 关闭模态框
const closeModal = () => {
  showModal.value = false;
};

// 添加节点
const addNode = () => {
  if (!inputValue.value) return; // 没有输入值则不操作

  const newNode = { title: inputValue.value, key: `${Date.now()}`, children: [] };
  if (selectedNodeKey.value) {
    const nodePosition = findNodePosition(selectedNodeKey.value, rightTreeData.value);
    if (nodePosition) {
      const { parent, index } = nodePosition;
      if (isChildNode.value) {
        if (parent) {
          parent.children[index].children.push(newNode);
        } else {
          rightTreeData.value[index].children.push(newNode);
        }
      } else {
        if (parent) {
          parent.children.splice(index + 1, 0, newNode);
        } else {
          rightTreeData.value.splice(index + 1, 0, newNode);
        }
      }
    }
  }
  closeModal();
};
// 删除节点
const deleteNode = () => {
  if (selectedNodeKey.value) {
    const nodePosition = findNodePosition(selectedNodeKey.value, rightTreeData.value);
    if (nodePosition) {
      const { parent, index } = nodePosition;
      if (parent) {
        parent.children.splice(index, 1);
      } else {
        rightTreeData.value.splice(index, 1);
      }
      selectedNodeKey.value = null;
      selectedKeys.value = [];
    }
  }
};
// 上移节点
const moveUpNode = () => {
  if (selectedNodeKey.value) {
    const { parent, index } =
      findNodePosition(selectedNodeKey.value, rightTreeData.value) || {};
    if (parent && index > 0 && isSecondLevelNode(selectedNodeKey.value)) {
      const [node] = parent.children.splice(index, 1);
      parent.children.splice(index - 1, 0, node);
    } else if (index > 0 && isSecondLevelNode(selectedNodeKey.value)) {
      const [node] = rightTreeData.value.splice(index, 1);
      rightTreeData.value.splice(index - 1, 0, node);
    }
  }
};
// 下移节点
const moveDownNode = () => {
  if (selectedNodeKey.value) {
    const { parent, index } =
      findNodePosition(selectedNodeKey.value, rightTreeData.value) || {};
    if (
      parent &&
      index < parent.children.length - 1 &&
      isSecondLevelNode(selectedNodeKey.value)
    ) {
      const [node] = parent.children.splice(index, 1);
      parent.children.splice(index + 1, 0, node);
    } else if (
      index < rightTreeData.value.length - 1 &&
      isSecondLevelNode(selectedNodeKey.value)
    ) {
      const [node] = rightTreeData.value.splice(index, 1);
      rightTreeData.value.splice(index + 1, 0, node);
    }
  }
};

// 判断是否为二级节点
const isSecondLevelNode = (key: string) => {
  return rightTreeData.value.some((node) =>
    node.children.some((child) => child.key === key)
  );
};

// 右侧树的点击事件
const handleRightTreeClick = (event, node) => {
  // 处理右侧树的点击事件，不更新标题
  console.log(":", node);
};

// 右侧树的选择事件
const handleRightTreeSelect = (keys, event) => {
  selectedKeys.value = keys;
  // 不更新标题
  console.log(":", keys);
};
const parentMenuOptions = ref([
  { key: "menu1", title: "Menu 1" },
  { key: "menu2", title: "Menu 2" },
  { key: "menu3", title: "Menu 3" },
]);
const selectedParentMenu = ref("");
const previewTemplate = () => {};

// 保存模板
const saveTemplate = () => {};

onMounted(() => {
  queryData();
});
</script>

<template>
  <div class="container">
    <div class="con">
      <!-- 左侧树 -->
      <div class="left-tree">
        <a-tree
          v-model:expandedKeys="expandedKeys"
          :selectedKeys="selectedKeys"
          v-model:checkedKeys="checkedKeys"
          :tree-data="treeData"
          @click="handleClick"
        >
          <template #title="{ title, key }">
            <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
            <template v-else>{{ title }}</template>
          </template>
        </a-tree>
      </div>

      <!-- 右侧树及按钮 -->
      <div class="right-content">
        <div class="right-header">
          <span>{{ title }}</span>
        </div>
        <div class="bbt">
          <a-button
            type="primary"
            size="small"
            @click="openModal(false)"
            :icon="h(PlusOutlined)"
            >添加同级节点</a-button
          >
          <a-button
            type="primary"
            size="small"
            @click="openModal(true)"
            :icon="h(PlusOutlined)"
            >添加下级节点</a-button
          >
          <a-button
            type="primary"
            size="small"
            @click="deleteNode"
            :icon="h(MinusOutlined)"
            >删除</a-button
          >
          <a-button
            type="primary"
            size="small"
            @click="moveUpNode"
            :icon="h(ArrowUpOutlined)"
            >上移</a-button
          >
          <a-button
            type="primary"
            size="small"
            @click="moveDownNode"
            :icon="h(ArrowDownOutlined)"
            >下移</a-button
          >
        </div>
        <a-tree
          v-model:expandedKeys="expandedKeys"
          :selectedKeys="selectedKeys"
          v-model:checkedKeys="checkedKeys"
          :tree-data="rightTreeData"
          @click="handleRightTreeClick"
          @select="handleRightTreeSelect"
        >
          <template #title="{ title, key, record }">
            <div class="tree-node-container">
              <span>{{ title }}</span>
              <!-- 添加textarea，仅对二级节点显示 -->
              <template v-if="isSecondLevelNode(key)">
                <a-textarea
                  v-model:value="value"
                  :rows="1"
                  :placeholder="findTypeByKey(key)"
                ></a-textarea>
              </template>
            </div>
          </template>
        </a-tree>
      </div>
    </div>

    <!-- 添加节点的模态框 -->
    <a-modal
      v-model:open="showModal"
      title="添加节点"
      ok-text="确定"
      cancel-text="取消"
      @ok="addNode"
      @cancel="closeModal"
    >
      <a-input v-model:value="inputValue" placeholder="请输入节点名称"></a-input>
    </a-modal>
    <!-- 底部操作栏 -->
    <div class="footer">
      <a-button type="primary" size="small" @click="previewTemplate">模板预览</a-button>
      <a-button type="primary" size="small" @click="saveTemplate">保存模板</a-button>
      <!-- <a-select
        v-model="selectedParentMenu"
        style="width: 200px"
        placeholder="选择上级菜单"
      >
        <a-select-option
          v-for="item in parentMenuOptions"
          :key="item.key"
          :value="item.key"
        >
          {{ item.title }}
        </a-select-option>
      </a-select> -->
    </div>
  </div>
</template>

<style scoped lang="less">
@import "./index.less";

/* 样式调整，根据需要修改 */
.container {
  display: flex;
  flex-direction: column;
}

.con {
  display: flex;
  margin-top: 0px;
}

.left-tree {
  // flex: 1;
  overflow: auto;
}

.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.right-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.right-content .ant-tree {
  margin-bottom: 10px;
}

textarea {
  margin-top: 5px;
  width: 420px;
}
.tree-node-container {
  display: flex;
  flex-direction: column;
}
.footer {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: #f0f2f5;
  border-top: 1px solid #d9d9d9;
  width: 10%;
}
</style>
